<?php

namespace Admin\Controller;

use Think\PageAdmin;
use Common\Support\Curl;
use Think\Upload;
use Common\Support\Excel;

/**
 * 订单管理控制器
 */
class OrderController extends BaseController
{

    /**
     * 初始化
     *
     * @return [type] [description]
     */
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 进行中订单
     * @return [type] [description]
     */
    public function index()
    {
        $prefix = C('DB_PREFIX');

        $count = M('order')->count();
        $page = new PageAdmin($count, C('PAGE_NUM'));

        $pages['show'] = $page->show();  //分页输出
        $pages['total'] = $count;  //总数
        $pages['lists'] = M('order a')
            ->order("a.id desc")
            ->limit($page->firstRow . ',' . $page->listRows)
            ->select();

        $this->seotitle = '进行中订单';
        $this->pages = $pages;
        $this->display();
    }

    /**
     * 历史订单
     * @return [type] [description]
     */
    public function history()
    {
        $prefix = C('DB_PREFIX');

        $count = M('order')->count();
        $page = new PageAdmin($count, C('PAGE_NUM'));

        $pages['show'] = $page->show();  //分页输出
        $pages['total'] = $count;  //总数
        $pages['lists'] = M('order a')
            ->order("a.id desc")
            ->limit($page->firstRow . ',' . $page->listRows)
            ->select();

        $this->seotitle = '历史订单';
        $this->pages = $pages;
        $this->display();
    }

    /**
     * 订单详情
     */
    public function detail()
    {
        $id = I('id');

        $order_info = M("order")->where(['id' => $id])->find();

        //审核员和门店信息
        $info = M("store s")
            ->join("wk_audit a on s.audit_user_id = a.id")
            ->field("s.*,a.mobile audit_mobile,a.company_name,a.name")
            ->where(['s.id' => $order_info['store_id']])
            ->find();

        $activity_info = M("activity")->where(['id' => $order_info['activity_id']])->find();

        $this->activity_info = $activity_info;
        $this->info = $info;
        $this->order_info = $order_info;
        $this->seotitle = '订单详情';
        $this->display();
    }

    public function demo()
    {

        $data = [
            'order_no' => '2019021954555710',
            'up_time' => 'xxxxx', //上画时间
            'is_down' => '0', //默认0 ，传1表示下画
            'down_time' => '',  //下画传时间，不下画传空

            //广告位信息，单个或者多个,当是系统广告位时ads_type=1,只需要传广告位id，后台查询后填充数据
            'order_ads' => [
                [
                    'ads_id' => 11,  //所属门店广告位id
                    'ads_type' => 1, //广告位类型 1=>系统广告位 2=>门店自定义
                    'filepath' => '', //如果有最终效果图，传值
                    //'ads_name'      => '门头位一',
                    //'height'        => 1000,
                    //'width'         => 1000,
                    //'filepath'      => '', //如果有最终效果图，传值
                    //'is_upper_air'  => 0, //是否高空

                    //广告块详细数据
                    'order_ads_detail' => [
                        [
                            'ads_detail_id' => 22,
                            //'ads_name'          => 'B1',
                            //'ads_type'          => 1, //块类型，1=>长方形 2=>圆形
                            //'x_axis'            => 100, //x轴坐标
                            //'y_axis'            => 100, //y轴坐标
                            //'height'            => 600, //高度
                            //'width'             => 100, //宽度
                            //'radius'            => '',  //半径
                            'remark' => 'xxx', //备注
                            'materiel_id' => 10, //材料id
                            //'materiel_name'     => 'KT板', //材料名称
                            'activity_image_id' => '10', //效果图id
                            //'activity_image_url'=> 'xxxxxx', //效果图路径
                        ],

                        [
                            'ads_detail_id' => 23,
                            //'ads_name'          => 'B2',
                            //'ads_type'          => 1, //块类型，1=>长方形 2=>圆形
                            //'x_axis'            => 100, //x轴坐标
                            //'y_axis'            => 100, //y轴坐标
                            //'height'            => 600, //高度
                            //'width'             => 100, //宽度
                            //'radius'            => '',  //半径
                            'remark' => 'xxx', //备注
                            'materiel_id' => 10, //材料id
                            //'materiel_name'     => 'KT板', //材料名称
                            'activity_image_id' => '10', //效果图id
                            //'activity_image_url'=> 'xxxxxx', //效果图路径
                        ],

                        [
                            'ads_detail_id' => 24,
                            //'ads_name'          => 'B3',
                            //'ads_type'          => 1, //块类型，1=>长方形 2=>圆形
                            //'x_axis'            => 100, //x轴坐标
                            //'y_axis'            => 100, //y轴坐标
                            //'height'            => 600, //高度
                            //'width'             => 100, //宽度
                            //'radius'            => '',  //半径
                            'remark' => 'xxx', //备注
                            'materiel_id' => 10, //材料id
                            //'materiel_name'     => 'KT板', //材料名称
                            'activity_image_id' => '10', //效果图id
                            //'activity_image_url'=> 'xxxxxx', //效果图路径
                        ],
                    ],
                ],

                //自定义广告位，只需要写入order_ads表，没有广告块
                [
                    'ads_type' => 2, //广告位类型 1=>系统广告位 2=>门店自定义
                    'ads_name' => '门头位一',
                    'height' => 200,
                    'width' => 200,
                    'materiel_id' => 10, //材料id
                    'activity_image_id' => '10', //效果图id
                    'filepath' => '', //如果有最终效果图，传值
                    'is_upper_air' => 0, //是否高空

                    //广告块详细数据
                    'order_ads_detail' => [],
                ],
            ]

        ];

        echo json_encode($data);
        //var_dump($data);
    }

    /**
     * 导出订单
     */
    public function exportByOrderNO()
    {
        $order_id = I('order_no');
        $store_id = I('store_id');

        $tmp = [];
        if ($store_id) {
            $order_arr = M('order')->where(['store_id' => $store_id])->select();
            foreach ($order_arr as $kk => $vv) {
                $dd = $this->orderDetail($vv['order_no']);
                $tmp[$kk] = $dd;
            }
        } else {
            $data = $this->orderDetail($order_id);
            $tmp[0] = $data;
        }


        /**创建excel对象*/
        vendor('PHPExcel.PHPExcel');
        vendor('PHPExcel.PHPExcel.Writer.Excel2007');
        $objPHPExcel = new \PHPExcel();
        /**设置样式*/
        //合并单元格
        //$objPHPExcel->getActiveSheet()->mergeCells('b1:d1');
        //$objPHPExcel->getActiveSheet()->mergeCells('e1:f1');
        //$objPHPExcel->getActiveSheet()->mergeCells('g1:i1');
        //设置单元格宽度
        //$objPHPExcel->getActiveSheet()->getColumnDimension('a')->setWidth(5);
        //$objPHPExcel->getActiveSheet()->getColumnDimension('b')->setWidth(5);
        //$objPHPExcel->getActiveSheet()->getColumnDimension('c')->setWidth(12);
        //$objPHPExcel->getActiveSheet()->getColumnDimension('d')->setWidth(12);
        //$objPHPExcel->getActiveSheet()->getColumnDimension('e')->setWidth(7);
        //$objPHPExcel->getActiveSheet()->getColumnDimension('f')->setWidth(30);
        //$objPHPExcel->getActiveSheet()->getColumnDimension('j')->setWidth(7);

        /**写入第一行数据*/
        //$objPHPExcel->getActiveSheet()->setCellValue('a1', $uid);
        //$objPHPExcel->getActiveSheet()->setCellValue('b1', $match_entry['team_name']);
        //$objPHPExcel->getActiveSheet()->setCellValue('e1', $match_entry['team_teacher']." ".$match_entry['team_contact']);
        //$objPHPExcel->getActiveSheet()->setCellValue('g1', $match_entry['team_contact']);
        //$objPHPExcel->getActiveSheet()->setCellValue('h1', $player_total.'人');
        //字体加粗改变大小
        //$objPHPExcel->getActiveSheet()->getStyle('a1:z1')->getFont()->setBold(true);
        //$objPHPExcel->getActiveSheet()->getStyle('a1:z1')->getFont()->setSize(16);


        /**标题*/
        $objPHPExcel->getActiveSheet()->getStyle('a2:z2')->getFont()->setBold(true);
        //$title = ['序号','背号','男步','女步','组别ID','组别名称','舞种','服务费','代表队','审核'];

        $title = ['订单号', '活动名称', '活动id', '订单状态描述', '门店id', '门店名', '经理', '门店手机号', '门店地址', '审核员名字', '审核员手机号',
            '上画时间', '下画时间', '审核结果', '是否下画'];
        $now = 'A';
        foreach ($title as $v) {
            $objPHPExcel->getActiveSheet()->setCellValue($now . '2', $v);
            $now++;
        }

        /**内容*/
        //记录索引
        $index = 1;
        //总服务费
        $amount = 0;
        foreach ($tmp as $k => $v) {

            // $content = [$index, $v['back_number'], implode(',', $male), implode(',', $female), $v['event_number'], $v['event_title'], $v['event_dances'],$v['event_fee'], $match_entry['team_name'], $status];
            $content = [$v['order_no'] . '', $v['activity_name'], $v['activity_id'], $v['order_status_msg'],
                $v['store_id'], $v['store_name'], $v['store_manager'], $v['store_mobiel'], $v['store_address'], $v['audit_name'], $v['audit_mobile'],
                $v['up_time'], $v['down_time'], $v['audit_result'], $v['is_down_msg']];
            $flag = 'A';
            $column = $index + 2;
            foreach ($content as $con) {
                $objPHPExcel->getActiveSheet()->setCellValue("$flag$column", $con);
                $flag++;
            }
            $index++;
            //$amount += $v['event_fee'];
        }
        /**尾行*/
        $lastIndex = $index + 2;
        //$objPHPExcel->getActiveSheet()->mergeCells("a$lastIndex:g$lastIndex");
        //$objPHPExcel->getActiveSheet()->setCellValue("a$lastIndex", '合计');
        //$objPHPExcel->getActiveSheet()->setCellValue("h$lastIndex", $amount);
        //  $objPHPExcel->getActiveSheet()->setCellValue("i$lastIndex", $match_entry['team_name']);
        // $objPHPExcel->getActiveSheet()->setCellValue("j$lastIndex", '确认');
        //表格边框
        /* for($i=2; $i<=$lastIndex; $i++){
             for($j='a'; $j<='h'; $j++){
                 $objPHPExcel->getActiveSheet()->getStyle("$j$i")->getBorders()->getTop()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
                 $objPHPExcel->getActiveSheet()->getStyle("$j$i")->getBorders()->getLeft()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
                 $objPHPExcel->getActiveSheet()->getStyle("$j$i")->getBorders()->getRight()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
                 $objPHPExcel->getActiveSheet()->getStyle("$j$i")->getBorders()->getBottom()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
             }
             //文本换行
             $objPHPExcel->getActiveSheet()->getStyle("d$i")->getAlignment()->setWrapText(true);
         }*/
        //$objPHPExcel->getActiveSheet()->getStyle("d2:d$lastIndex")->getAlignment()->setWrapText(true);
        //$objPHPExcel->getActiveSheet()->getStyle("a1:h$lastIndex")->getBorders()->getAllBorders()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);//全部加边框
        // 导出文件
        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
        $fileName = '订单表.xlsx';
        // 输出
        ob_end_clean();//清除缓冲区,避免乱码
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');

        $objWriter->save('php://output');
    }

    public function orderDetail($order_no)
    {

        $order_info = M('order')->where(['order_no' => $order_no])->find();
        if (!$order_no) {
            $this->ajaxReturn(['status' => false, 'code' => 1001, 'msg' => '订单号异常', 'data' => []]);
        }

        $activity_info = M('activity')->where(['id' => $order_info['activity_id']])->find();
        $store_info = M('store')->where(['id' => $order_info['store_id']])->find();
        $audit_info = M('audit')->where(['id' => $store_info['audit_user_id']])->find();
        $ads_info = M('order_ads a')
            ->field('a.id,a.ads_name,a.width,a.height,a.filepath,a.ads_type,a.materiel_id,a.activity_image_id,a.is_upper_air,a.num')
            ->where(['a.order_no' => $order_no])->select();

        foreach ($ads_info as $k => $v) {
            $ads_info[$k]['detail'] = M("order_ads_detail b")
                ->field(' b.ads_name,b.ads_type,b.x_axis,b.y_axis,b.width,b.height,b.remark,b.materiel_id,b.materiel_name,b.activity_image_id,b.activity_image_url,b.activity_image_name')
                ->where(['order_ads_id' => $v['id']])->select();

            if ($v['ads_type'] == 1) {//自定义广告
                $ads_info[$k]['filepath'] = C('DOMAIN') . '/' . $v['filepath'];
            }
        }

        foreach ($ads_info as $k => $v) {
            if ($v['ads_type'] == 2) {
                $materiel = M('materiel')->where(['id' => $v['materiel_id']])->field('name')->find();
                $activity_image = M('activity_image')->where(['id' => $v['activity_image_id']])->field('image_url,image_name')->find();
                $ads_info[$k]['materiel_name'] = $materiel['name'];
                $ads_info[$k]['activity_image_url'] = $activity_image['image_url'];
                $ads_info[$k]['activity_image_name'] = $activity_image['image_name'];
            }
        }

        $data = [
            'activity_name' => $activity_info['name'],  //活动名称
            'activity_id' => $activity_info['id'],  //活动id
            'order_no' => $order_no,   //订单号
            'order_status' => $order_info['order_status'], //订单状态
            'order_status_msg' => $order_info['order_status'], //订单状态
            'store_id' => 9,
            'store_name' => $store_info['store_name'], //门店名字
            'store_manager' => $store_info['manager_name'], //店长名字
            'store_mobiel' => $store_info['mobile'], //店长电话
            'store_address' => $store_info['address'], //上画地址
            'audit_name' => $audit_info['name'], //审核员名字
            'audit_mobile' => $audit_info['mobile'], //审核员电话
            'up_time' => $order_info['up_time'], //上画时间
            'down_time' => $order_info['down_time'], //下画时间
            'audit_result' => $order_info['audit_result'], //审核不通过原因
            'is_down' => $order_info['is_down'], //是否下画
            'is_down_msg' => $order_info['is_down'] == 0 ? '否' : '是',
            'ads_info' => $ads_info
        ];

        return $data;

        //$this->ajaxReturn(['status' => true, 'code' => 1000, 'msg' => '订单详情查询成功', 'data' => $data]);
    }

    /**
     * 高空报价
     */
    public function upper_fee()
    {
        $order_no = I('order_no');
        $parter_fee = I('parter_fee');
        $upper_fee = I('upper_fee');

        $data = ['parter_fee' => $parter_fee, 'upper_fee' => $upper_fee, 'order_status' => 12,
            'upper_fee_time' => time(), 'upper_fee_user' => 1
        ];

        $r = M("order")->where(['order_no' => $order_no])->save($data);
        if ($r) {
            $this->ajaxReturn(['status' => true, 'code' => 1000, 'msg' => '高空报价完成']);
        } else {
            $this->ajaxReturn(['status' => false, 'code' => 1000, 'msg' => '系统错误']);
        }
    }

    /**
     * 接受订单--分配师傅
     */
    public function order_commit()
    {
        $order_no = I('order_no');
        $worker = I('worker');
        $worker_first = I('worker_first');
        $up_num = I('up_num');
        $service_type = I('service_type');

        $info = M('order')->where(['order_no' => $order_no])->find();
        if ($info['worker_id'] != 0) {
            $this->ajaxReturn(['status' => false, 'code' => 1002, 'msg' => '请勿重新分配订单']);
        }

        $r = M('order')->where(['order_no' => $order_no])->save(['worker_id' => $worker_first, 'service_type' => $service_type, 'worker_order_status' => 1]);
        if ($r) {
            $this->ajaxReturn(['status' => true, 'code' => 1000, 'msg' => '订单分配成功']);
        } else {
            $this->ajaxReturn(['status' => false, 'code' => 1001, 'msg' => '订单分配失败']);
        }
    }
}